﻿using System.Collections.Generic;
using System.Threading.Tasks;
using SQLBuilder.Repositories;
using EasyTask.Models;
using EasyTask.EasyEnum;
using EasyTask.EasyHelper;
using EasyTask.EasyService;

namespace EasyService
{
    public class TaskService
    {

        SqliteRepository db = new SqliteRepository(ConnstringConfig.connStr);

        /// <summary>
        /// 获取所有的任务
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<Tasks>> GetAllTasksAsync()
        {
            return await db.FindListAsync<Tasks>(x => x.State != -7);
        }

        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <returns></returns>
        public async Task<int> UpdateTaskAsync(string JobName, ServiceState state)
        {
            Tasks tasks = new Tasks
            {
                JobName = JobName,
                State = (int)state,
                DisplayStateDesc = EnumHelper.GetDescription(state)
            };
            return await db.UpdateAsync(tasks);
        }

        /// <summary>
        /// 当服务手动停止后要执行的操作
        /// </summary>
        /// <returns></returns>
        public async Task<int> WhenManualStopExcuteAsync()
        {
            //更新 启动/暂停的为停止     (手动停止后,不启动)
            //更新 启动/暂停的为准备启动 (手动停止后,启动)
            var sql = $@"
UPDATE Base_Tasks SET State = -9,DisplayStateDesc='手动从服务中停止' WHERE ManualStopIsStart=0 AND State IN (0,1,3,-3);
UPDATE Base_tasks SET State =  0,DisplayStateDesc='准备启动'         WHERE ManualStopIsStart=1 
";
            return await db.ExecuteBySqlAsync(sql);
        }
    }
}